package com.quanyan.stadium.web.admin;

import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.encrypt.CustomCodec;
import com.quanyan.stadium.api.req.*;
import com.quanyan.stadium.api.req.admin.*;
import com.quanyan.stadium.api.req.admin.ReqSearchGameEvent;
import com.quanyan.stadium.api.resp.RespOfficialGameTeam;
import com.quanyan.stadium.api.resp.admin.RespGameEventDetail;
import com.quanyan.stadium.entity.TbGameCommonParameter;
import com.quanyan.stadium.entity.TbGameEvent;
import com.quanyan.stadium.service.GameEventService;
import com.quanyan.stadium.service.admin.AdminGameEventService;
import com.quanyan.stadium.service.gameRules.GameRoundService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/admin/api/stadium/gameEvent")
public class GameEventController {


    private static Logger logger = LoggerFactory.getLogger(GameEventController.class);

    @Autowired
    private AdminGameEventService adminGameEventService;

    @Autowired
    private GameEventService gameEventService;

    @Autowired
    private GameRoundService gameRoundService;



    /**
     * 赛事编辑----赛事完结
     *
     * */
    @RequestMapping(value="/finishGameEvent", method = RequestMethod.POST)
    public APIResponse<?> finishGameEvent(@RequestBody @Valid ReqFinishGameEvent reqFinishGameEvent, BindingResult result, HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {
        if(result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        try{
            return gameEventService.finishGameEvent(reqFinishGameEvent, (Integer) request.getAttribute("uid"));
        }catch (Exception e) {
            logger.error("协议:赛事完结, 名称:{}, 错误原因:{}","finishGameEvent", e);
            return APIResponse.returnFail("服务器异常");
        }
    }


    /**
     * 赛事状态 更新
     *
     * */
    @RequestMapping(value="/updateGameEventStatus", method = RequestMethod.POST)
    public APIResponse<?> updateGameEventStatus(@RequestBody @Valid ReqGameEventStatusUpdate reqGameEventStatusUpdate, BindingResult result, HttpServletRequest request)  {
        if (result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        if (adminGameEventService.updateGameEventStatus(reqGameEventStatusUpdate)) {
            return APIResponse.returnSuccess();
        }
        return APIResponse.returnFail("赛事状态更新失败:赛事不存在或者赛事状态已被更新");
    }

    /**
     * 搜索赛事信息
     *
     * */
    @RequestMapping(value="/searchTbGameEventList", method = RequestMethod.POST)
    public APIResponse<RespGameEventDetail> searchTbGameEventList(@RequestBody @Valid ReqSearchGameEvent reqSearchGameEvent, BindingResult result, HttpServletRequest request)  {
        if (result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        return APIResponse.returnSuccess(adminGameEventService.queryTbGameEventList(reqSearchGameEvent));
    }

    /**
     * 创建积分赛事
     *
     *
     *
     * */
    @RequestMapping(value="/createIntegrateGame", method = RequestMethod.POST)
    public APIResponse<?> createIntegrateGame(@RequestBody @Valid ReqCreateGameEventExtraMsg event, BindingResult result, HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {
        if (result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        return adminGameEventService.createGameEvent(event);
    }

    /**
     * 获官方赛列表(包含场馆赛\分区\全国)
     *
     *
     *
     * */
    @CustomCodec(includes = {"id","name","placeId"})
    @RequestMapping(value="/queryOfficialGameEvent", method = RequestMethod.POST)
    public APIResponse<?> queryOfficialGameEvent(@RequestBody @Valid ReqOfficialGameEvent reqOfficialGameEvent, BindingResult result, HttpServletRequest request)  {
        if (result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        List<TbGameEvent> temp = adminGameEventService.queryOfficialGameEventByPlaceIdAndCategoryId(reqOfficialGameEvent);
        return APIResponse.returnSuccess(temp);
    }

    /**
     * 给俱乐部进行授权,来进行积分赛的发布
     *
     * */
    @RequestMapping(value="/authorizeClub", method = RequestMethod.POST)
    public APIResponse<?> authorizeClub(@RequestBody @Valid ReqAuthorizeClub reqAuthorizeClub, BindingResult result, HttpServletRequest request)  {
        if (result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        return adminGameEventService.authorizeClub(reqAuthorizeClub);
    }

    /**
     * 给俱乐部进行取消授权
     *
     * */
    @RequestMapping(value="/closeClubAuthorize", method = RequestMethod.POST)
    public APIResponse<?> closeClubAuthorize(@RequestBody Map<String, Object> map, BindingResult result, HttpServletRequest request)  {
        if (null == map || null == map.get("clubAuthorizeId")) {
            return APIResponse.returnFail("clubAuthorizeId");
        }
        return adminGameEventService.closeClubAuthorize(Integer.parseInt(map.get("clubAuthorizeId")+""));

    }

    /**
     *  赛事编辑-----更新赛事的组数和晋级队伍数目 (混合赛制,生成轮次)
     *
     * */
    @RequestMapping(value="/updateGroupNumAndRankNum", method = RequestMethod.POST)
    public APIResponse<?> updateGroupNumAndRankNum(@RequestBody @Valid ReqGroupNumAndRankNum reqGroupNumAndRankNum, BindingResult result) throws Exception {
        if(result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        try{
            return gameEventService.updateGroupNumAndRankNum(reqGroupNumAndRankNum);
        }catch (Exception e) {
            logger.error("web端协议:更新赛事的组数和晋级队伍数目;名称:{}, 错误原因:{}","updateGroupNumAndRankNum", e);
            return APIResponse.returnFail("服务器异常");
        }
    }

    /**
     * 赛事编辑-----赛事管理详情(生成轮次)
     *
     * */
    @RequestMapping(value="/gameRoundAndGameTeam", method = RequestMethod.POST)
    public APIResponse<?> gameRoundAndGameTeam(@RequestBody ReqId reqId, BindingResult result) throws Exception {
        if(result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        if (null == reqId.getGameEventId()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        try{
            return gameEventService.gameRoundAndGameTeam(reqId.getGameEventId());
        }catch (Exception e) {
            logger.error("web端协议:赛事管理详情;名称:{}, 错误原因:{}","gameRoundAndGameTeam", e);
            return APIResponse.returnFail("服务器异常");
        }
    }

    /**
     * 赛事编辑-----混合赛制配置分组数目和晋级人数
     *
     * */
    @RequestMapping(value="/getGroupNmAndRankNumByTeamNum", method = RequestMethod.POST)
    public APIResponse<?> getGroupNmAndRankNumByTeamNum(@RequestBody ReqId reqId, BindingResult result) throws InvocationTargetException, IllegalAccessException {
        if(result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        if (null == reqId.getTeamNum()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        if (reqId.getTeamNum()<5) {
            return APIResponse.returnFail("队伍数目过少(至少5个队伍),无法分组");
        }
        try{
            return APIResponse.returnSuccess(gameRoundService.getGroupNmAndRankNumByTeamNum(reqId.getTeamNum()));
        }catch (Exception e) {
            logger.error("web端协议:存在分组的赛事,获取分组数目和晋级数目,根据队伍数目, 名称:{}, 错误原因:{}","getGroupNmAndRankNumByTeamNum", e);
            return APIResponse.returnFail("服务器异常");
        }
    }



    /**
     * 俱乐部授权场馆列表
     * @param reqIdAndPage
     * @return
     */
    @RequestMapping(value="/authorizeClubPlaceList", method = RequestMethod.POST)
    public APIResponse<?> authorizeClubPlaceList(@RequestBody ReqIdAndPage reqIdAndPage)  {
        if (null == reqIdAndPage && null == reqIdAndPage.getClubId()) {
            return APIResponse.returnFail("clubId不能为空");
        }
        return adminGameEventService.authorizeClubPlaceList(reqIdAndPage);
    }

    /**
     * 获取某场馆的队伍积分排名
     *
     * */
    @RequestMapping(value="/placeScoreRankList", method = RequestMethod.POST)
    public APIResponse<PageObj<List<RespOfficialGameTeam>>> placeScoreRankList(@RequestBody @Valid ReqIdAndPage reqIdAndPage, BindingResult result) throws InvocationTargetException, IllegalAccessException {
        if(result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        if (null == reqIdAndPage.getGameEventId()) {
            return APIResponse.returnFail("gameEventId不能为空");
        }
        try{
            return gameEventService.placeScoreRankList(reqIdAndPage.getGameEventId(), reqIdAndPage.getPageNo(), reqIdAndPage.getPageSize());
        }catch (Exception e) {
            logger.error("协议:获取某场馆的队伍积分排名;名称:{}, 错误原因:{}","placeScoreRankList", e);
            return APIResponse.returnFail("服务器异常");
        }
    }

    /**
     * 根据城市id查询banner图
     */
    @RequestMapping(value = "/getBannerList",method = RequestMethod.POST)
    public APIResponse<?> getBannerList(){
        ReqId reqId = new ReqId();
        reqId.setCityId(6);
        return adminGameEventService.getBannerList(reqId);
    }

    /**
     * 增加banner图
     */
    @RequestMapping(value = "/addBannerList",method = RequestMethod.POST)
    public APIResponse<?> addBannerList(@RequestBody ReqBannerList bannerList, BindingResult result){
        if (result.hasErrors()){
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        return adminGameEventService.addBannerList(bannerList);
    }

    /**
     * 编辑banner图
     */
    @RequestMapping(value = "/editBanner",method = RequestMethod.POST)
    public APIResponse<?> editBanner(@RequestBody @Valid ReqBanner banner, BindingResult result){
        if (result.hasErrors()){
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        return adminGameEventService.editBanner(banner);
    }

    /**
     * 设置优先级
     */
    @RequestMapping(value = "/setBannerPriority",method = RequestMethod.POST)
    public APIResponse<?> setBannerPriority(@RequestBody @Valid ReqBannerPriorityList priorityList , BindingResult result){
        if (result.hasErrors()){
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        return adminGameEventService.setBannerPriority(priorityList);
    }

    /**
     * 删除banner图
     */
    @RequestMapping(value = "/deleteBanner",method = RequestMethod.POST)
    public APIResponse<?> deleteBanner(@RequestBody Map<String, Integer> map){
        return adminGameEventService.deleteBanner(map.get("id"));
    }

    /**
     * 查询配置项列表
     */
    @RequestMapping(value = "/getCommonParameterList",method = RequestMethod.POST)
    public APIResponse<?> getCommonParameterList(@RequestBody ReqParamer reqParamer){
        return APIResponse.returnSuccess(adminGameEventService.getCommonParameterList(reqParamer));
    }

    /**
     * 添加配置项
     */
    @RequestMapping(value = "/addCommonParameter",method = RequestMethod.POST)
    public APIResponse<?> addCommonParameter(@RequestBody TbGameCommonParameter parameter){
        return APIResponse.returnSuccess(adminGameEventService.addCommonParameter(parameter));
    }

    /**
     * 编辑配置项
     */
    @RequestMapping(value = "/editCommonParameter",method = RequestMethod.POST)
    public APIResponse<?> editCommonParameter(@RequestBody TbGameCommonParameter parameter){
        return APIResponse.returnSuccess(adminGameEventService.editCommonParameter(parameter));
    }

    /**
     * 不启用配置项
     */
    @RequestMapping(value = "/changeCommonParameter",method = RequestMethod.POST)
    public APIResponse<?> changeCommonParameter(@RequestBody ReqParamer reqParamer){
        return APIResponse.returnSuccess(adminGameEventService.changeCommonParameter(reqParamer.getId(),reqParamer.getStatus()));
    }
    /**
     * 授权俱乐部列表
     */
    @RequestMapping(value = "/authorizeClubList",method = RequestMethod.POST)
    public APIResponse<?> authorizeClubList(){
        return APIResponse.returnSuccess(adminGameEventService.authorizeClubList());
    }




}
